package com.woniuxy.bookmall.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniuxy.bookmall.config.AliPayProperties;
import com.woniuxy.bookmall.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
@Slf4j
public class AliPayController {
    @Autowired
    AliPayProperties aliPayProperties ;
    @Autowired
    AlipayClient alipayClient ;

    @Autowired
    AlipayTradePagePayRequest alipayRequest ;

    @Autowired
    OrderService orderService ;

    @RequestMapping("/ali/pay")
    @ResponseBody
    public String pay(@RequestParam("widOut_trade_no") String wIDout_trade_no,
                      @RequestParam("wIdSubject")String wIDsubject,
                      @RequestParam("wIdTotal_amount") BigDecimal wIDtotal_amount,
                      @RequestParam(value = "widBody",defaultValue = "") String WIDbody) throws AlipayApiException {

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ wIDout_trade_no +"\","
                + "\"total_amount\":\""+ wIDtotal_amount +"\","
                + "\"subject\":\""+ wIDsubject +"\","
                + "\"body\":\""+ WIDbody +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result ;
    }


    //异步
   /* @RequestMapping("/ali/notifyUrl")
    public String notifyUrl(HttpServletRequest request){

        return "redirect:/book/index" ;
    }*/

    //同步
    @RequestMapping("/ali/returnUrl")
    public String returnUrl(HttpServletRequest request) throws AlipayApiException {
        log.info("支付宝回调接口开始:"+new Date());
        //如果支付成功 ，需要修改订单的状态
        Map<String, String> params = new HashMap<>(8);
        Map<String, String[]> requestParams = request.getParameterMap();

        //定义一个 订单编号
        String orderNum = request.getParameter("out_trade_no");
        log.info("支付的订单编号是:{}",orderNum);

        for (Map.Entry<String, String[]> stringEntry : requestParams.entrySet()) {
            String[] values = stringEntry.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(stringEntry.getKey(), valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, aliPayProperties.getAlipay_public_key(),
                aliPayProperties.getCharset(), aliPayProperties.getSign_type());

        if (!signVerified) {
            log.info("支付回调的验签失败--->支付失败!");
            return "error" ;
        }else {
            //修改订单状态
            log.info("修改订单状态--->:");
            orderService.modifyOrderOfStatus(orderNum);
        }
        // 支付成功之后 ，去订单详情页面
        return "redirect:/book/index" ;
    }
}